#!/usr/bin/python
# -*- coding：utf-8 -*-

import pandas as pd
import numpy as np
import datetime
import  csv
from xgboost import XGBRegressor as XGBR
import xgboost as xgb
from sklearn.model_selection import KFold, cross_val_score as CVS, train_test_split as TTS
from time import time
from sklearn.metrics import mean_squared_error as MSE, r2_score
import pickle


# pre函数，预测函数，无返回值，只需要根据输入的路径来输出一个预测结果的csv文件
def Model_construcion(input_path = "../data/电量.csv", model_path = "../model/dlxgboost.dat"):
	data = pd.read_csv(input_path, engine='python', encoding="utf_8_sig")
	data['SDATE'] = pd.to_datetime(data['SDATE'])
	dataset = data.copy()
	# 分离数据集
	data = pd.DataFrame({'temphigh': data['temphigh'], 'templow': data['templow'],
						 'is_holiday': data['is_holiday'], 'wind': data['wind'],
						 'humidity': data['humidity'], 'tempavg': data['tempavg'],
						 'hour': data['hour'], 'weekofyear': data['weekofyear'],
						 'dayofweek': data['dayofweek'], 'season': data['season'],
						 'total': data['total']})
	X = data.drop(['total'], axis=1)
	y = data['total']
	X_train, X_test, Y_train, Y_test = TTS(X, y, test_size=0.3, random_state=420)
	dfull = xgb.DMatrix(X, y)
	param = {'silent': True
		, 'obj': 'reg:linear'
		, "max_depth": 8
		, "eta": 0.01
		, "gamma": 0
		, "lambda": 1
		, "alpha": 0
		, "colsample_bytree": 1
		, "colsample_bylevel": 0.4
		, "colsample_bynode": 1
		, "nfold": 5}
	num_round=1000
	time0 = time()
	#cvresult = xgb.cv(param, dfull, num_round)
	dtrain = xgb.DMatrix(X_train, Y_train)
	dtest = xgb.DMatrix(X_test, Y_test)
	bst = xgb.train(param, dtrain, num_round)
	# 保存模型
	pickle.dump(bst, open(model_path, "wb"))
	ypreds = bst.predict(dtest)
	print('预测6小时准确率%5.2f' % r2_score(Y_test, ypreds))
	yfpreds = bst.predict(dfull)  # 传统接口predict
	dataset.index = dataset['SDATE'].tolist()
	dataset = dataset.drop(['SDATE'], axis=1)
	dataset['yfpreds'] = yfpreds
	dataset = dataset.resample('D').sum()
	print('预测每天准确率%5.2f' % r2_score(dataset['total'],dataset['yfpreds']))
	data = pd.DataFrame({'SDATE': dataset.index, 'total': dataset.total, 'yfpreds': dataset.yfpreds})
	data1 = data.copy()
	data['SDATE'] = data['SDATE'].dt.date
	data.index = range(data.shape[0])
	data1 = data1.drop(['SDATE'], axis=1)
	data1 = data1.resample('M').sum()
	print('预测每月准确率')
	print((data1['total']-(abs(data1['total']-data1['yfpreds'])))/data1['total'])
	
if __name__ == '__main__':
	Model_construcion(input_path="../data/电量.csv", model_path="../model/dlxgboost.dat")